# Definition for singly-linked list.
from typing import Optional


class ListNode:
    def __init__(self, val=0, next=None):
        self.val = val
        self.next = next


def create_linked_list(nums):
    if not nums:
        return None

    head = ListNode(nums[0])
    current = head
    for i in range(1, len(nums)):
        current.next = ListNode(nums[i])
        current = current.next

    return head


l1 = create_linked_list([2, 4, 3])
l2 = create_linked_list([5, 6, 4])
# print(l1.val, l2.val)


class Solution:
    def addTwoNumbers(
        self, l1: Optional[ListNode], l2: Optional[ListNode]
    ) -> Optional[ListNode]:
        head = ListNode(0)
        current = head
        add = 0
        while l1 is not None or l2 is not None:
            val1 = l1.val if l1 is not None else 0
            val2 = l2.val if l2 is not None else 0
            total = val1 + val2 + add
            current.next = ListNode(total % 10)
            current = current.next
            add = total // 10
            l1 = l1.next if l1 is not None else None
            l2 = l2.next if l2 is not None else None
        if add > 0:
            current.next = ListNode(add)
        return head.next


solution = Solution()
result = solution.addTwoNumbers(l1, l2)
while result is not None:
    print(result.val)
    result = result.next
